package lhc.learn.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

import java.util.Date;

/**
 * Created by lihon on 2016/3/25.
 */
public class TimeServerHandler extends ChannelHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buff = (ByteBuf) msg;
        byte[] arr = new byte[buff.readableBytes()];
        buff.readBytes(arr);
        String message = new String(arr, "UTF-8");
        System.out.println("receive a new message :" + message);
        byte[] result = new Date().toString().getBytes("UTF-8");
        buff = Unpooled.copiedBuffer(result);
        ctx.write(buff);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
